package com.hyjx.framework.component.fastdfs;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 图片处理类
 *
 * @author 王亚南
 */
public class ImageHelp {

    public static void main(String[] args) {


    }


    /**
     * 压缩图片
     *
     * @param is    图片流
     * @param scale 压缩比  (0~1)
     * @param etx   图片格式
     * @return
     */
    public static byte[] resizeImg(InputStream is, double scale, String ext) {
        BufferedImage bufferedImage;
        try {
            bufferedImage = ImageIO.read(is);
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            width = parseDoubleToInt(width * scale);
            height = parseDoubleToInt(height * scale);
            Image image = bufferedImage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage outputImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics graphics = outputImage.getGraphics();
            graphics.drawImage(image, 0, 0, null);
            graphics.dispose(); //释放图像资源
            ByteArrayOutputStream outp = new ByteArrayOutputStream();
            ImageIO.write(outputImage, ext, outp);
            return outp.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * InputStream转换byte[]
     *
     * @param is
     * @return
     */
    public static byte[] toBArray(InputStream is) {
        ByteArrayOutputStream outp = new ByteArrayOutputStream();
        int ch = 0;
        try {
            while ((ch = is.read()) != -1)
                outp.write(ch);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] b = outp.toByteArray();
        return b;
    }

    /**
     * 将double类型的数据转换为int，四舍五入原则
     *
     * @param sourceDouble
     * @return
     */
    private static int parseDoubleToInt(double sourceDouble) {
        int result = 0;
        result = (int) sourceDouble;
        return result;
    }
}
